import { ISMEventData } from "../../GameLogic";

const { ccclass, property, menu } = cc._decorator;

@ccclass
@menu('game/TimeLimitedComponent')
export default class TimeLimitedComponent extends cc.Component {

    @property(cc.Label)
    countdownLbl: cc.Label = null;

    @property(cc.Sprite)
    radialSpr: cc.Sprite = null;

    private _countdown = 0;
    private _timer = null
    private _total = 1;

    startClock(countdown: number, total: number) {

        this._countdown = countdown;
        this._total = total;

        this.updateUI();

        const timer = this.clockTimer.bind(this);
        this.schedule(timer, 1, countdown, 0);
        this._timer = timer;

        this.radialSpr.fillRange = countdown / total;

        cc.tween(this.radialSpr).to(countdown, { fillRange: 0 }).start();
    }

    stopClock() {
        this.unschedule(this._timer);
        this._timer = null;
        cc.Tween.stopAllByTarget(this.radialSpr);
    }

    protected updateUI() {
        this.countdownLbl.string = this._countdown + '';
    }

    protected onTimeOver() {
        const evt = new cc.Event.EventCustom('sm-event', true);

        const data: ISMEventData = {
            type: 'game-over'
        };

        evt.setUserData(data);
        this.node.dispatchEvent(evt);
    }

    protected clockTimer() {
        this._countdown--;
        if (this._countdown < 0) {
            // dosomething;
            this.onTimeOver();
            this.stopClock();
            return;
        }

        this.updateUI();
    }
}
